package com.xsp.controller;

import com.alibaba.fastjson.JSON;
import com.xsp.entity.CommonResult;
import com.xsp.entity.ResponseCode;
import com.xsp.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author xsp
 * @date 2024/2/5
 * @desc
 */
@Controller
@RequestMapping("user2")
public class User2Controller {
    /**
     * 获取用户列表
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        // 查询用户列表
        // 假设Model查询到了
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "tom1", "111"));
        userList.add(new User(2, "tom2", "111"));
        userList.add(new User(3, "tom3", "111"));
        userList.add(new User(4, "tom4", "111"));
        // 以前玩法：将数据保存到request中，然后转发到userList.jsp
        ModelAndView mv = new ModelAndView();
        // request.setAttribute("userList",userList)
        mv.addObject("userList", userList);
        // 转发，request.getRequestDispatcher("WEB-INF/jsp/userlist.jsp").forward(res,resp)
//        mv.setViewName("/WEB-INF/jsp/userlist.jsp");
        mv.setViewName("userlist"); // 由视图解析器自动拼凑成上述地址格式
        return mv;
    }

    /**
     * 回去用户列表--简写形式
     *
     * @return 视图名
     */
    @RequestMapping("list1")
    public String list1(Model model) {
        // ModelAndView中的Model由springmvc创建
        // 查询用户列表
        // 假设Model查询到了
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "tom1", "111"));
        userList.add(new User(2, "tom2", "111"));
        userList.add(new User(3, "tom3", "111"));
        userList.add(new User(4, "tom4", "111"));
        model.addAttribute("userList", userList);
        // ModelAndView中的View由springmvc创建
        return "userlist";
    }

    /**
     * 根据用户名查询信息
     */
    @RequestMapping("findlist")
    public ModelAndView findList(HttpServletRequest request, HttpServletResponse response) {
        // 查询用户列表--模糊查询
        String username = request.getParameter("username");
        // 假设Model查询到了
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "tom1" + username, "111"));
        userList.add(new User(2, "tom2" + username, "111"));
        userList.add(new User(3, "tom3" + username, "111"));
        userList.add(new User(4, "tom4" + username, "111"));
        ModelAndView mv = new ModelAndView();
        mv.addObject("userList", userList);
        mv.setViewName("userlist"); // 由视图解析器自动拼凑成上述地址格式
        return mv;
    }

    /**
     * 根据用户名查询信息
     */
    @RequestMapping("findlist2")
    public ModelAndView findList2(
            @RequestParam(name = "name", required = false) String username,
            @RequestParam(required = false, defaultValue = "1") Integer pageIndex) {
        // 假设Model查询到了
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "tom1" + username, "111"));
        userList.add(new User(2, "tom2" + username, "111"));
        userList.add(new User(3, "tom3" + username, "111"));
        userList.add(new User(4, "tom4" + username, "111"));
        ModelAndView mv = new ModelAndView();
        mv.addObject("userList", userList);
        mv.setViewName("userlist"); // 由视图解析器自动拼凑成上述地址格式
        System.out.println(pageIndex);
        return mv;
    }

    /**
     * 根据用户名查询信息
     */
    @RequestMapping(value = "findlist3", method = {RequestMethod.POST})
    public ModelAndView findList3(
            @RequestParam(name = "name", required = false) String username,
            @RequestParam(required = false, defaultValue = "1") Integer pageIndex) {
        // 假设Model查询到了
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "tom1" + username, "111"));
        userList.add(new User(2, "tom2" + username, "111"));
        userList.add(new User(3, "tom3" + username, "111"));
        userList.add(new User(4, "tom4" + username, "111"));
        ModelAndView mv = new ModelAndView();
        mv.addObject(userList); // key默认为userList
        mv.setViewName("userlist"); // 由视图解析器自动拼凑成上述地址格式
        System.out.println(pageIndex);
        return mv;
    }

    @RequestMapping(value = "add", method = {RequestMethod.GET})
    public String add() {
//        try {
        System.out.println("打开新增界面");
        // 模拟异常
        int a = 10 / 0;
        return "useradd";
//        } catch (Exception e) {
//            // 手动处理异常
//            return "500";
//        }
    }

    @RequestMapping(value = "add1", method = {RequestMethod.GET})
    public String add1() {
        System.out.println("打开新增异步请求界面");
        return "useradd1";
    }

    @RequestMapping(value = "add2", method = {RequestMethod.GET})
    public String add2() {
        System.out.println("打开新增异步请求界面");
        return "useradd2";
    }

    @RequestMapping(value = "add", method = {RequestMethod.POST})
    // @ModelAttribute自动解析同步提交的表单元素，生成javaBean,保存到属性中
//    public String add(@ModelAttribute User user) {
    public String add(User user) {
        System.out.println("保存新增操作");
        System.out.println(user);
        return "redirect:list";// 重定向到/user/list
    }

    @RequestMapping(value = "add1", method = {RequestMethod.POST})
    public String add1(String user) {
        // user为json字符串，需要手动转化为JavaBean
        User user1 = JSON.parseObject(user, User.class);
        System.out.println("保存新增操作");
        System.out.println(user);
        System.out.println(user1);
        return "redirect:list";// 重定向到/user/list
    }

    @RequestMapping(value = "add2", method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult add2(@RequestBody User user) {
        System.out.println("保存新增操作");
        System.out.println(user);
        return CommonResult.success(user, "保存成功");
    }

    @RequestMapping(value = "add3", method = {RequestMethod.GET})
    public String add3() {
        return "useradd3";
    }

    @RequestMapping(value = "add3", method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult add3(HttpServletRequest request, User user,
                             @RequestParam(value = "photo", required = false) MultipartFile file) {
        if (!file.isEmpty()) {
            // 设置保存路径
            String path = request.getServletContext().getRealPath("/statics/images");
            String newFileName = UUID.randomUUID().toString() + file.getOriginalFilename();
            File saveFile = new File(path, newFileName);
            try {
                file.transferTo(saveFile);
                return CommonResult.success(user, "保存成功");
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e.getCause());
            }
        }
        return CommonResult.error("请上传图片！");
    }

    @RequestMapping(value = "add4", method = {RequestMethod.GET})
    public String add4() {
        return "useradd4";
    }

    @RequestMapping(value = "add4", method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult add4(User user) {
        // todo：使用model保存user到数据库
        return CommonResult.success(user, "保存成功");
    }

    @GetMapping(value = "add5")
    public String add5() {
        System.out.println("执行handler--add5");
        return "useradd5";
    }

    @PostMapping(value = "add5")
    @ResponseBody
    public CommonResult add5(@RequestBody User user) {
        // todo：使用model保存user到数据库
        return CommonResult.success(user, "保存成功");
    }

    @RequestMapping(value = "modify", method = {RequestMethod.GET})
    public String modify() {
        System.out.println("打开修改界面");
        return "";
    }

    @RequestMapping(value = "modify", method = {RequestMethod.POST})
    public String modify(String name) {
        System.out.println("保存修改");
        return "";
    }

    /**
     * 判断用户名重名
     *
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("checkname")
    @ResponseBody
    public CommonResult checkName(String username) {
        // 假设admin已被使用-模拟
//        int a = 10 / 0;
        if ("admin".equals(username)) {
            return CommonResult.response(ResponseCode.EXISTS, null, "用户名已被使用");
        } else {
            return CommonResult.success("用户名可以使用");
        }
    }

    // 局部异常处理器，处理当前控制器中所有的异常信息
    @ExceptionHandler({RuntimeException.class})
    @ResponseBody
    public CommonResult handleException(RuntimeException e, HttpServletRequest request) {
        return CommonResult.error(e.getMessage());
    }
}
